import * as THREE from 'three';
import dat from 'dat.gui';
import { initStats, initRenderer, initCamera, addHouseAndTree } from '../util';

export function init01(width, height) {
  // 初始化性能统计
  const stats = initStats();
  // 初始化渲染器
  const renderer = initRenderer(width, height);
  // 初始化相机
  const camera = initCamera(width, height);
  // 创建场景
  const scene = new THREE.Scene();
  // 添加光源
  const ambientLight = new THREE.AmbientLight('#606008', 1);
  scene.add(ambientLight);
  // 添加聚光灯
  const spotLight = new THREE.SpotLight(0xffffff, 1, 180, Math.PI / 4);
  spotLight.shadow.mapSize.set(2048, 2048);
  spotLight.position.set(-30, 40, -10);
  spotLight.castShadow = true;
  scene.add(spotLight);
  // 添加房子和树
  addHouseAndTree(scene);
  // 安装变量控制器
  stepControls();
  // 渲染
  render();

  function render() {
    stats.update();
    renderer.render(scene, camera);
    requestAnimationFrame(render);
  }

  function stepControls() {
    const controls = {
      intensity: ambientLight.intensity,
      ambientColor: ambientLight.color.getStyle(),
      disableSpotlight: false
    };
    // 控制光源强度
    const gui = new dat.GUI();
    gui.add(controls, 'intensity', 0, 3, 0.1).onChange(() => {
      ambientLight.color = new THREE.Color(controls.ambientColor);
      ambientLight.intensity = controls.intensity;
    });
    // 控制光源颜色
    gui.addColor(controls, 'ambientColor').onChange(() => {
      ambientLight.color = new THREE.Color(controls.ambientColor);
      ambientLight.intensity = controls.intensity;
    });
    // 是否启用聚光灯
    gui.add(controls, 'disableSpotlight').onChange(e => {
      spotLight.visible = !e;
    });
    return controls;
  }
}
